package com.jq.jqaicode.common.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * vue部署项目
 */
public class VueBuilder {


    /**
     * 构建 Vue 项目 执行系统命令（支持 Windows / Linux）
     * @param workingDir Vue 项目的根目录路径
     * @throws IOException
     * @throws InterruptedException
     */

    public static void runCommand(String workingDir)
            throws IOException, InterruptedException {
        File projectDir = new File(workingDir);
        ProcessBuilder pb = new ProcessBuilder();
        pb.directory(projectDir);
        pb.redirectErrorStream(true); // 合并 stdout 和 stderr
        // Windows 用 cmd /c，Linux/Mac 用 sh -c
        boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");
        if (isWindows) {
            pb.command("cmd.exe", "/c", "npm install && npm run build && npx rimraf node_modules");
        } else {
            pb.command("sh", "-c", "npm install && npm run build && npx rimraf node_modules");

        }
        Process process = pb.start();

        // 实时读取控制台输出
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }

        int exitCode = process.waitFor();
        System.out.println("打包完成，退出码：" + exitCode);
    }
}
